const TokenKey: string = 'token'

// 获取浏览器参数
export function getQueryString (name: string) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  const url = window.location.search || window.location.href
  const search = url.split('?').pop() || ''
  const d = decodeURI(search)
  const r = d.match(reg)
  if (r != null) return unescape(r[2]); return null
}

// 获取指定key
export function getToken (key: string = TokenKey) {
  let data = sessionStorage.getItem(key)
  if (!data) data = getQueryString(key)
  if (!data) return null
  try {
    return JSON.parse(data)
  } catch (e) {
    return data
  }
}

// 设置key
export function setToken (key: string, value: any) {
  if (typeof value === 'object') value = JSON.stringify(value)
  sessionStorage.setItem(key, value)
}

// 清除指定key
export function removeToken (key?: string) {
  sessionStorage.removeItem(key || TokenKey)
}

// 清除所有
export function removeAll () {
  sessionStorage.clear()
}
